package com.gitee.ixtf.vertx.internal.converter

import com.gitee.ixtf.vertx.ParameterConverter
import com.gitee.ixtf.vertx.internal.rc
import graphql.schema.DataFetchingEnvironment
import io.vertx.core.eventbus.Message
import io.vertx.ext.web.RoutingContext
import jakarta.ws.rs.DefaultValue
import jakarta.ws.rs.QueryParam
import java.lang.reflect.Parameter

class QueryParamParameterConverter(
    private val parameter: Parameter,
) : ParameterConverter<Any?> {
  private val key by lazy { parameter.getAnnotation(QueryParam::class.java).value }
  private val defaultValue by lazy { parameter.getAnnotation(DefaultValue::class.java)?.value }
  private val converter by lazy { implicitConverter(parameter) }
  private val convert by lazy { defaultValue?.let { converter.convert(it) } }

  override suspend fun convert(env: DataFetchingEnvironment) = convert(env.rc())

  override suspend fun convert(rc: RoutingContext) =
      rc.queryParam(key)?.joinToString(",")?.let { converter.convert(it) } ?: convert

  override suspend fun convert(message: Message<*>) =
      message.headers().get(key)?.let { converter.convert(it) } ?: convert
}
